<?php
	///////////////////////////////////////////////////////////////////////////////////////////////////
	//	REPORT ERROR PAGE
	//	WRITTEN BY: TRAVIS THORNTON
	//	12-07-2009
	//
	//	What this page does:
	//	1) Shows a form to submit an error based upon input to this file
	//	2) Add the error to the errorsreported table if user
	//	3) Change the value automatically if a manager
	//	4) Allows managers to approve errors, which will fix the problem
	//	5) Allows managers to add "Bonus" time for employees. This time is extra for getting paid for an outing that does not need to be tracked for ot compensation
	//	6) Allows managers to add events to timesheets
	//
	// 	Future work:
	//	1) Edit existing error report instead of allowing multiple reports on the same event
	// 	2) Event sorting for added events. They must be added at the end of the day now
	////////////////////////////////////////////////////////////////////////////////////////////////////
	session_start();
	require_once 'php_includes.php';

	//Make sure logged in
	checkLogin();
	
	//Set these session variables so it can return to the correct timesheet
	if(isset($_POST['period']) && isset($_POST['usertime']))
	{
		$_SESSION['usertime'] = $_POST['usertime'];
		$_SESSION['period'] = $_POST['period'];
	}

	//default messages
    $display = -1;
	$error = "";

    //see if it is a manager for the employee
    $manager = 0;
    $sql = "SELECT ManagerID FROM Employee WHERE EmployeeID = '" . $_POST['usertime'] . "'";  
    sqlConnect();
    $results = sqlQueryNoLog($sql);
    sqlExit();
        
    if(mysql_result($results, 0, 0) == $_SESSION['tmsUserID'])
    {
		//Yes, it was the manager for this employee. allow them to edit it.
        $manager = 1;
    }
    
	//if we need to approve a reported error, make sure it is a manager logged on
    if($manager == 1 && $_POST['action'] == "approve")
    {
		//select the correct entry in the correct payperiod
        $sql = 'SELECT Entry'.($_POST['offset']).' FROM PayPeriod WHERE EmployeeID = \''.$_POST['usertime'].'\' AND PeriodStart = \''.$_POST['period'].'\'';
        sqlConnect();
        $sqlresult = sqlQuery($sql);
        sqlExit();
                
		//original event string
        $event_str = mysql_result($sqlresult, 0, 0);
                
        if($event_str != "")
        {	
			//if it needs to be deleted
            if($_POST['correction'] == "delete")
            {
				//replace the event needed to be changed with nothing (remove it)
                $event_str = str_replace("|" . $_POST['original'], "", $event_str);
                $event_str = str_replace($_POST['original'], "", $event_str);//in case it is the first event
            }
            else
            {
				//replace the original with the correction
                $event_str = str_replace($_POST['original'], $_POST['correction'], $event_str);
            }
             
			//update the db with the corrected event
            $sql = 'UPDATE `'.$dbname.'`.`PayPeriod` SET Entry'.($_POST['offset']).' = \''.$event_str.'\' WHERE EmployeeID = \''.$_POST['usertime'].'\' AND PeriodStart = \''.$_POST['period'].'\'';

            sqlConnect();
            $sqlresult = sqlQuery($sql);
            sqlExit();
                    
            $display = 2;
        }
        
        //delete the error report
        $sql = "DELETE FROM ReportedErrors WHERE EmployeeID='".$_POST['usertime']."' AND ErrorPeriodStart='".$_POST['period']."' AND CorrectionEvent='".$_POST['errortime']."'";
        sqlConnect();
        $sqlresult = sqlQuery($sql);
        sqlExit();
    }
	//we need to add an event to the timesheet
	else if($_POST['action'] == "finish_event" && $manager == 1)
    {
		//will hold the added event data
		$changed_format = $_POST['event'] . "@" . $_POST['period'] . " ";			
		
		//extract the new time
		$correct_time = explode(":", $_POST['newtime']);
				
		if((int)$correct_time[0] > 12 ||(int)$correct_time[0] < 1 )
		{
			$error = "Hours are not formatted correctly (HH:MM)";
		}
		if((int)$correct_time[0] > 59 ||(int)$correct_time[0] < 1)
		{
			$error = "Minutes are not formatted correctly (HH:MM)";
		}
					
		$new_hr = (int)$correct_time[0];
		$new_min = (int)$correct_time[1];
			
		//format time for the timestamp
		//24 hour format
		if($_POST['newperiod'] == "pm")
		{
			$new_hr = $new_hr +12;
		}
		//hour padding		
		if($new_hr < 10)
		{
			$changed_format = $changed_format. "0";
		}
			
		//add to string
		$changed_format = $changed_format . $new_hr . ":";
			
		//min padding
		if($new_min < 10)
		{
			$changed_format = $changed_format. "0";
		}
			
		//put together a new formatted string
		$changed_format = $changed_format. $new_min . ":00";		

		if($error == "")
		{		
			//get the entry
			$sql = 'SELECT Entry'.($_POST['offset']).' FROM PayPeriod WHERE EmployeeID = \''.$_POST['usertime'].'\' AND PeriodStart = \''.$_POST['period'].'\'';
			sqlConnect();
			$sqlresult = sqlQuery($sql);
			sqlExit();
						
			//grab the event string
			$event_str = mysql_result($sqlresult, 0, 0);
							
			$event_str = $event_str . "|" . $changed_format;
					
			//update the db instantly
			$sql = 'UPDATE `'.$dbname.'`.`PayPeriod` SET Entry'.($_POST['offset']).' = \''.$event_str.'\' WHERE EmployeeID = \''.$_POST['usertime'].'\' AND PeriodStart = \''.$_POST['period'].'\'';
							
			sqlConnect();
			$sqlresult = sqlQuery($sql);
			sqlExit();
						
			//success screen
			$display = 6;
		}
    }
	//if we need to add an event, display the proper form
	else if($_POST['action'] == "addevent" && $manager == 1)
    {
        $display = 5;
    }
	//if the action is to change the bonus and it is a manager logged on, show the correct form
    else if($_POST['action'] == "changebonus" && $manager == 1)
    {
        $display = 4;
    }
	//if we need to process the bonus change and it is a manager, process it
    else if($_POST['action'] == "finish_bonus" && $manager == 1)
    {
		//get the correct entry
        $sql = 'SELECT Entry'.($_POST['offset']).' FROM PayPeriod WHERE EmployeeID = \''.$_POST['usertime'].'\' AND PeriodStart = \''.$_POST['period'].'\'';
        sqlConnect();
        $sqlresult = sqlQuery($sql);
        sqlExit();
         
		//get the event string
        $event_str = mysql_result($sqlresult, 0, 0);
		
		//make the new format
        $current_format = "4@" . $_POST['newtime'];
		
        if($event_str != "")
        {	
			//replace the original with the new
            $event_str = str_replace($_POST['previous_time'], $current_format, $event_str);  
              
			//update the table
            $sql = 'UPDATE `'.$dbname.'`.`PayPeriod` SET Entry'.($_POST['offset']).' = \''.$event_str.'\' WHERE EmployeeID = \''.$_POST['usertime'].'\' AND PeriodStart = \''.$_POST['period'].'\'';
                    
            sqlConnect();
            $sqlresult = sqlQuery($sql);
            sqlExit();
                 
			//display the results page
            $display = 3;
        }
    }
	// we want to edit an event display the correct page
    else if($_POST['action'] == "submit_error")
	{
		$display = 0;
	}
	//process the error
	else if($_POST['action'] == "finish_error")
    {
		//set formats
		$current_format = $_POST['timestamp'];
		$changed_format = $_POST['timestamp'];
				
		//if we are deleting the event		
		if($_POST['delete'][0] == "yes")
		{
			$changed_format = "delete";
		}
		else
		{
			//extract the new time
			$correct_time = explode(":", $_POST['newtime']);
				
			if((int)$correct_time[0] > 12 ||(int)$correct_time[0] < 1 )
			{
				$error = "Hours are not formatted correctly (HH:MM)";
			}
			if((int)$correct_time[0] > 59 ||(int)$correct_time[0] < 1)
			{
				$error = "Minutes are not formatted correctly (HH:MM)";
			}
			$current_head = explode(" ", $_POST['timestamp']);
			
			//put together a new formatted string
			$changed_format = $current_head[0] . " ";
					
			$new_hr = (int)$correct_time[0];
			$new_min = (int)$correct_time[1];
			
			//format time for the timestamp
			//24 hour format
			if($_POST['newperiod'] == "pm")
			{
				$new_hr = $new_hr +12;
			}
			//hour padding		
			if($new_hr < 10)
			{
				$changed_format = $changed_format. "0";
			}
			
			//add to string
			$changed_format = $changed_format . $new_hr . ":";
			
			//min padding
			if($new_min < 10)
			{
				$changed_format = $changed_format. "0";
			}
			
			//put together a new formatted string
			$changed_format = $changed_format. $new_min . ":00";		
		}
				
		//if there was no error and it is a user
		if($error == "" && $manager == 0)
		{
			//fix the reason so it does not fail the query
			$input = str_replace(";", "", $_POST['reason']);
			$input = addslashes($input);
					
			//insert the error report
			$sql = 'INSERT INTO `' . $dbname .'`.`ReportedErrors` (`EmployeeID`, `ErrorPeriodStart`, `EntryNo`, `CorrectionTimestamp`, `CorrectionEvent`, `EventTimeCorrection`, `Reason`) VALUES (\''.$_POST['usertime'].'\', \''.$_POST['period'].'\', \''.($_POST['offset']-1).'\', \''.$current_format.'\', CURRENT_TIMESTAMP, \''.$changed_format.'\', \''.$input.'\');';
			sqlConnect();
			$sqlresult = sqlQuery($sql);
			sqlExit();
					
			//display the success screen
			$display = 1;
		}
		//if no error and manager
		else if($error == "" && $manager == 1)
		{
			//get the entry
			$sql = 'SELECT Entry'.($_POST['offset']).' FROM PayPeriod WHERE EmployeeID = \''.$_POST['usertime'].'\' AND PeriodStart = \''.$_POST['period'].'\'';
			sqlConnect();
			$sqlresult = sqlQuery($sql);
			sqlExit();
					
			//grab the event string
			$event_str = mysql_result($sqlresult, 0, 0);
					
			if($event_str != "")
			{
				//replace the event
				if($changed_format == "delete")
				{
					$event_str = str_replace("|" . $current_format, "", $event_str);
					$event_str = str_replace($current_format, "", $event_str);//in case it is the first event
				}
				else
				{
					$event_str = str_replace($current_format, $changed_format, $event_str);
				}
					
				//update the db instantly
				$sql = 'UPDATE `'.$dbname.'`.`PayPeriod` SET Entry'.($_POST['offset']).' = \''.$event_str.'\' WHERE EmployeeID = \''.$_POST['usertime'].'\' AND PeriodStart = \''.$_POST['period'].'\'';
						
				sqlConnect();
				$sqlresult = sqlQuery($sql);
				sqlExit();
					
				//success screen
				$display = 3;
			}
		}
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Report Error</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<?php
	//if error, display it
    if($error != "")
    {
        echo "<p class=\"php_message\">";
        echo $error;
        echo "</p>";
    }
	
	//if we need to display the error reporting form
    if($display == 0)
    {   
		if($manager == 1)
		{
			echo "<p>Change time:<br/>\n";
		}
		else
		{
			echo "<p>Report Error:<br/>\n";
		}
               
		//get the event and write it
        if($_POST['timestamp'])
        {
            $data = explode("@", $_POST['timestamp']);
            switch($data[0])
            {
                case "0":
                    echo "Clocked in";
                    break;
                                
                case "1":
                    echo "Clocked out";
                    break;
                                
                case "2":
                    echo "Went to lunch";
                    break;
                                
                case "3":
                    echo "Came back from lunch";
                    break;
                    
                case "4":
                    echo "Bonus time";
                    break;

                default:
                    echo"Error";
            }
        
			//extract dates + time
            $date_data = explode(" ", $data[1]);
            $time = explode(":", $date_data[1]);
            echo " at ";
            
            //write time (format to 12hr)
            $period = "AM";
            if($time[0] >= 12)
            {
                $period = "PM";
                if($time[0] > 12)
                {
                    $time[0] = $time[0] - 12;
                }
            }
            echo (int)$time[0] . ":" . $time[1] . " ". $period . " on ";
            
            //write date
            echo date("m/d/y", strtotime($_POST['period'] . " + ".($_POST['offset']-1)." days"));
        }
        
        echo "<br/>\n";
        echo "</p>\n";
        echo "<form action=\"reporterror.php\" method=\"post\">\n";
        
        echo "<input type=\"hidden\" name=\"action\"value=\"finish_error\" />";
        echo "<input type=\"hidden\" name=\"usertime\"value=\"" . $_POST['usertime'] . "\" />";
        echo "<input type=\"hidden\" name=\"period\"value=\"" . $_POST['period'] . "\" />";                         
        echo "<input type=\"hidden\" name=\"offset\" value=\"". $_POST['offset'] ."\"/>";
        echo "<input type=\"hidden\" name=\"timestamp\" value=\"". $_POST['timestamp'] ."\"/>";
        
        echo "<div class=\"left_side\">\n";
        echo "  Delete Event:<br/>\n";
        echo "  Correct value (HH:MM):<br/>\n";
		
		//manager does not need a reason
        if($manager != 1){ echo "  Correction Reason:<br/>\n";}
		
        echo "</div>\n";
        echo "<div class=\"middle_cont\">\n";
        echo "<input type=\"checkbox\" name=\"delete[]\" value=\"yes\"/><br/>\n";
        echo "  <input type=\"text\" name=\"newtime\" size=\"4\" value=\"";
		
		//pad hour
		if((int)$time[0] < 10) { echo "0";}
		
		echo (int)$time[0] . ":" . $time[1] . "\"/> <select name=\"newperiod\"><option value=\"am\"";
        
		//default am if it is am
		if($period == "AM" ) { echo "selected=\"selected\""; }
        echo ">AM</option><option value=\"pm\"";
		
		//default pm if it was pm
        if($period == "PM" ) { echo "selected=\"selected\""; }
        echo ">PM</option></select><br/>\n";
		
		//manager does not need a reason
        if($manager != 1){  echo "  <textarea rows=\"4\" cols=\"40\" name=\"reason\"></textarea>\n"; }
		
        echo "</div>\n";
        echo "<p>\n";
        echo "<input type=\"submit\" value=\"Submit Error\" class=\"button\"/>\n";
        echo "</p>\n";
        echo "</form>\n";
    }
	//if user submitted an error
    else if($display == 1)
    {
        echo "<p>";
        echo "Error submitted for approval.";
        echo "<br/>";
        echo "<input type=\"submit\" value=\"Okay\" class=\"button\" onclick=\"javascript:window.opener.location.href='timesheet.php'; window.close();\"/>";
        echo "</p>";
    }
	// if manager approves a change submitted by a user
	else if($display == 2)
    {
        echo "<p>";
        echo "Event change approved.";
        echo "<br/>";
        echo "<input type=\"submit\" value=\"Okay\" class=\"button\" onclick=\"javascript:window.opener.location.href='errorsreported.php'; window.close();\"/>";
        echo "</p>";
    }
	//if manager edits a error
	else if($display == 3)
    {
        echo "<p>";
        echo "Event changed.";
        echo "<br/>";
        echo "<input type=\"submit\" value=\"Okay\" class=\"button\" onclick=\"javascript:window.opener.location.href='timesheet.php'; window.close();\"/>";
        echo "</p>";
    }
	//Allows editing of bonus time (manager only)
	//This shows a form to submit back to this php
	else if($display == 4)
    {
        echo "<p>Change \n";
        
		//explode bonus to array
        $data = explode("@",$_POST['bon']);   
        if($_POST['bon'])
        {
            echo "Bonus Time on ";
            
            //write date
            echo date("m/d/y", strtotime($_POST['period'] . " + ".($_POST['offset']-1)." days"));
        }
        
        echo "<br/>\n";
        echo "</p>\n";
        echo "<form action=\"reporterror.php\" method=\"post\">\n";
		//Hidden form elements
        echo "<input type=\"hidden\" name=\"action\"value=\"finish_bonus\" />";
        echo "<input type=\"hidden\" name=\"usertime\"value=\"" . $_POST['usertime'] . "\" />";
        echo "<input type=\"hidden\" name=\"period\"value=\"" . $_POST['period'] . "\" />";                         
        echo "<input type=\"hidden\" name=\"offset\" value=\"". $_POST['offset'] ."\"/>";
        echo "<input type=\"hidden\" name=\"previous_time\" value=\"". $_POST['bon'] ."\"/>";
        echo "<div class=\"left_side\">\n";      
        echo "Correct value (In minutes):<br/>\n";  
        echo "</div>\n";
        echo "<div class=\"middle_cont\">\n";
        echo "<input type=\"text\" name=\"newtime\" size=\"4\" value=\"". $data[1]. "\"/><br/>\n";
        echo "</div>\n";
        echo "<p>\n";
        echo "<input type=\"submit\" value=\"Submit Error\" class=\"button\"/>\n";
        echo "</p>\n";
        echo "</form>\n";
    }
	// This will display a form to add an event to an employee's day (manager only)
	else if($display == 5)
	{
		echo "<p>\n"; 
        echo "Add event on ";
            
        //write date
        echo date("m/d/y", strtotime($_POST['period'] . " + ".($_POST['offset']-1)." days"));
		
		echo "<br/><br/> Please note: This will appear below all of the other events in the column<br/>No error checking will be done at this time due to incorrect time results";
        
        echo "<br/>\n";
        echo "</p>\n";
        echo "<form action=\"reporterror.php\" method=\"post\">\n";
		//Hidden form elements
        echo "<input type=\"hidden\" name=\"action\"value=\"finish_event\" />";
        echo "<input type=\"hidden\" name=\"usertime\"value=\"" . $_POST['usertime'] . "\" />";
        echo "<input type=\"hidden\" name=\"period\"value=\"" . $_POST['period'] . "\" />";                         
        echo "<input type=\"hidden\" name=\"offset\" value=\"". $_POST['offset'] ."\"/>";
        echo "<div class=\"left_side\">\n";      
        echo "Event:<br/>\n"; 
		echo "Time (HH:MM):<br/>\n"; 		
        echo "</div>\n";
        echo "<div class=\"middle_cont\">\n";
		echo "<select name=\"event\"><option value=\"0\">Clock in</option><option value=\"2\">To Lunch</option><option value=\"3\">Back from Lunch</option><option value=\"1\">Clock out</option></select><br/>";
        echo "<input type=\"text\" name=\"newtime\" size=\"4\" value=\"00:00\"/> <select name=\"newperiod\"><option value=\"am\">AM</option><option value=\"pm\">PM</option></select><br/>\n";
        echo "</div>\n";
        echo "<p>\n";
        echo "<input type=\"submit\" value=\"Add Event\" class=\"button\"/>\n";
        echo "</p>\n";
        echo "</form>\n";
	}
	// This will display the results of adding that event to the employee's day
	// returns to timesheet.php
	else if($display == 6)
	{
		echo "<p>";
        echo "Event Added.";
        echo "<br/>";
        echo "<input type=\"submit\" value=\"Okay\" class=\"button\" onclick=\"javascript:window.opener.location.href='timesheet.php'; window.close();\"/>";
        echo "</p>";
	}
	//generic error. returns to the main.php
    else
    {
        echo "<p>";
        echo "Error.";
        echo "<br/>";
        echo "<input type=\"submit\" value=\"Okay\" class=\"button\" onclick=\"javascript:window.opener.location.href='main.php'; window.close();\"/>";
        echo "</p>";
    }
    
    ?>
</body>
</html>